﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Medianamik.UI.Controls;
using Medianamik.Core.Logging;

namespace Medianamik.UI.SecurityManagement
{
	public partial class RoleList : BasePage
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				BindControls();
				
			}
		}

		private void BindControls()
		{
			var roles = from role in Roles.GetAllRoles()
						select new { Name = role };

			GridRoles.DataSource = roles.OrderBy(r=>r.Name);
			GridRoles.DataBind();
		}

        protected void GridRoles_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.Web.UI.GridItemType.Item
                || e.Item.ItemType == Telerik.Web.UI.GridItemType.AlternatingItem)
            {
                var cmdDelete = e.Item.FindControl("cmdDelete") as ConfirmedImageButton;
                var enabled = Roles.GetUsersInRole((string)DataBinder.GetPropertyValue(e.Item.DataItem, "Name")).Length == 0;
                cmdDelete.Enabled = enabled;
                cmdDelete.ImageUrl = enabled
                    ? "/medianamik/images/Icones/Ico_Supprimer.gif"
                    : "/medianamik/images/Icones/Ico_SupprimerInactif.gif";
            }
        }

		protected void GridRoles_ItemCommand(object sender, CommandEventArgs e)
		{
			switch (e.CommandName.ToLowerInvariant())
			{
				case "deleterole":
                    string roleName = e.CommandArgument.ToString();
                    var logger = new ActivityLogger();
                    logger.Log(new LoggableObject(roleName, LogEntryType.Role), "Role Deleted");
                    Roles.DeleteRole(roleName);
					BindControls();
					break;
			}
		}
	}
}
